package com.ling.module1sbbyyds.service.news.usercenter;

import com.github.yitter.idgen.YitIdHelper;
import com.ling.sbbyyds.entity.users.User;
import com.ling.sbbyyds.entity.users.UserAtt;
import com.ling.sbbyyds.interaction.vo.UserAttVo;
import com.ling.sbbyyds.interaction.vo.UserFriendVo;
import com.ling.module1sbbyyds.utils.UserThreadLocal;
import com.ling.sbbyyds.imagetools.ImageUtils;
import com.ling.sbbyyds.interaction.ResultVo;
import com.ling.sbbyyds.mapper.user.UserAttMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * 关注用户
 */
@Service
public class UserAttService {

    @Autowired(required = false)
    private UserAttMapper userAttMapper;

    @Autowired(required = false)
    private UserService userService;

    /**
     * 关注用户
     *
     * @param beiUserId 要关注的用户id
     * @param flag      true：进行关注 false：取消关注
     * @return
     */
    public ResultVo attUser(Long beiUserId, Boolean flag) {
        try {
            if (ObjectUtils.isEmpty(beiUserId) || ObjectUtils.isEmpty(flag)) {
                return ResultVo.fail("参数错误！");
            }
            // 获取发布者
            Map<String, Object> userData = UserThreadLocal.get();
            User user = (User) userData.get("user");
            if (beiUserId.equals(user.getId())) {
                return ResultVo.fail("不能关注自己！");
            }


            //判断是否关注
            boolean attUserFlag = getAttUserFlag(user.getId(), beiUserId, true);
            //是否关注成功
            boolean attFlag;
            //进行关注
            if (flag) {
                if (attUserFlag) {
                    return ResultVo.fail("已经关注！");
                }
                //判断是否存在记录
                boolean haveCount = getAttUserFlag(user.getId(), beiUserId, null);
                //存在，修改state
                if (haveCount) {
                    attFlag = setAttUser(user.getId(), beiUserId, 1);
                    //不存在，插入记录
                } else {
                    attFlag = insertAttUser(user.getId(), beiUserId);
                }
                if (attFlag) {
                    return ResultVo.success(null, "关注成功！");
                }
                return ResultVo.fail("关注失败！");
                //取消关注
            } else {
                if (!attUserFlag) {
                    return ResultVo.fail("你未关注！");
                }
                //修改state
                attFlag = setAttUser(user.getId(), beiUserId, 0);
                if (attFlag) {
                    return ResultVo.success(null, "取消关注成功！");
                }
                return ResultVo.fail("取消关注失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("操作失败！");
        }

    }

    /**
     * 获取关注用户列表
     *
     * @param page
     * @param limit
     * @return
     */
    public ResultVo getAttUserList(Integer page, Integer limit) {
        if (ObjectUtils.isEmpty(page) || ObjectUtils.isEmpty(limit)) {
            return ResultVo.fail("参数错误！");
        }
        Map<String, Object> userData = UserThreadLocal.get();
        User user = (User) userData.get("user");
        //计算分页
        int limitStart = (page - 1) * limit;
        //获取关注列表
        ArrayList<UserAtt> attUserList = userAttMapper.getAttUserList(user.getId(), limitStart, limit);
        //返回的数据
        ArrayList<UserAttVo> attUserListVo = new ArrayList<>();
        //总条数
        Integer count = 0;
        //有数据
        if (!ObjectUtils.isEmpty(attUserList)) {
            //获取总条数
            count = userAttMapper.getAttUserListCount(user.getId());
            //获取用户名和头像
            for (UserAtt userAtt : attUserList) {
                UserAttVo userAttVo = new UserAttVo();
                userAttVo.setUserId(userAtt.getBeiUserId());
                User userInfo = userService.getUserInfo(userAtt.getBeiUserId());
                userAttVo.setHeadImage(ImageUtils.convertImageUrl(userInfo.getAvatar()));
                userAttVo.setUserName(userInfo.getUserName());
                attUserListVo.add(userAttVo);
            }
        }
        return ResultVo.success(attUserListVo).put("count", count);
    }


    /**
     * 获取好友用户列表
     *
     * @param page
     * @param limit
     * @return
     */
    public ResultVo getFriendsList(Integer page, Integer limit) {
        if (ObjectUtils.isEmpty(page) || ObjectUtils.isEmpty(limit)) {
            return ResultVo.fail("参数错误！");
        }
        // 获取发布者
        Map<String, Object> userData = UserThreadLocal.get();
        User user = (User) userData.get("user");
        //计算分页
        int limitStart = (page - 1) * limit;
        //获取关注列表
        ArrayList<UserAtt> attUserList = userAttMapper.getFriendsList(user.getId(), limitStart, limit);

        //返回的数据
        ArrayList<UserFriendVo> attUserListVo = new ArrayList<>();
        //总条数
        Integer count = 0;
        //有数据
        if (!ObjectUtils.isEmpty(attUserList)) {
            //获取总条数
            count = userAttMapper.getAttUserListCount(user.getId());
            //获取用户名和头像
            for (UserAtt userAtt : attUserList) {
                UserFriendVo userAttVo = new UserFriendVo();
                userAttVo.setUserId(userAtt.getUserId());
                User userInfo = userService.getUserInfo(userAtt.getUserId());
                userAttVo.setHeadImage(ImageUtils.convertImageUrl(userInfo.getAvatar()));
                userAttVo.setUserName(userInfo.getUserName());
                attUserListVo.add(userAttVo);
            }
        }
        return ResultVo.success(attUserListVo).put("count", count);
    }


    /**
     * 判断用户有是否关注 某用户   或   是否存在记录
     *
     * @param userId    进行关注的id
     * @param beiUserId 要关注的用户id
     * @return
     */
    public boolean getAttUserFlag(Long userId, Long beiUserId, Boolean flag) {
        try {
            if(ObjectUtils.isEmpty(userId)){
                return false;
            }
            Example example = new Example(UserAtt.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            criteria.andEqualTo("beiUserId", beiUserId);
            if (!ObjectUtils.isEmpty(flag)) {
                criteria.andEqualTo("state", flag);
            }
            int i = userAttMapper.selectCountByExample(example);
            return i > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 修改关注 状态  (修改)
     *
     * @param userId    进行关注的id
     * @param beiUserId 要关注的用户id
     * @param state     1.关注  0.取消关注
     * @return
     */
    public boolean setAttUser(Long userId, Long beiUserId, Integer state) {
        try {
            Example example = new Example(UserAtt.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            criteria.andEqualTo("beiUserId", beiUserId);
            UserAtt userAtt = new UserAtt();
            userAtt.setUserId(userId);
            userAtt.setBeiUserId(beiUserId);
            userAtt.setTime(new Date());
            userAtt.setAttId(YitIdHelper.nextId());
            userAtt.setState(state);
            int i = userAttMapper.updateByExampleSelective(userAtt, example);
            return i > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 进行关注 （插入关注记录）
     *
     * @param userId    进行关注的id
     * @param beiUserId 要关注的用户id
     * @return
     */
    public boolean insertAttUser(Long userId, Long beiUserId) {
        try {
            UserAtt userAtt = new UserAtt();
            userAtt.setUserId(userId);
            userAtt.setBeiUserId(beiUserId);
            userAtt.setAttId(YitIdHelper.nextId());
            userAtt.setState(1);
            userAtt.setTime(new Date());
            int i = userAttMapper.insertSelective(userAtt);
            return i > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
